package ar.edu.utn.frsf.tpae.a2013.g03.persistencia.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;

import ar.edu.utn.frsf.tpae.a2013.g03.persistencia.dao.CentroCostoDao;
import ar.edu.utn.frsf.tpae.a2013.g03.persistencia.model.CentroCosto;
import ar.edu.utn.frsf.tpae.a2013.g03.persistencia.model.Empleado;

public class CentroCostoHibernateDao implements CentroCostoDao {

	private static SessionFactory sessionFactory = configureSessionFactory();
    private static org.hibernate.service.ServiceRegistry serviceRegistry;

      private static SessionFactory configureSessionFactory() throws HibernateException {
          Configuration configuration = new Configuration();
          configuration.configure();
          serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();        
          sessionFactory = configuration.buildSessionFactory(serviceRegistry);
          return sessionFactory;
      }
	
	@Override
	public CentroCosto persistir(CentroCosto centroCosto) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.saveOrUpdate(centroCosto);
		session.getTransaction().commit();
		session.close();
		
		return centroCosto;
	}

	@Override
	public void eliminar(CentroCosto centroCosto) {
		// TODO Auto-generated method stub
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<CentroCosto> listar() {
		Session session = sessionFactory.openSession();
		Query query = session.createQuery("from " + CentroCosto.class.getName());
		return query.list();
	}

	@Override
	public CentroCosto buscarPorNombre(String centroCosto) {
		Session session = sessionFactory.openSession();
		Query query = session.createQuery("from " + Empleado.class.getName() + " where usr_nom = :nombre");
		query.setString("nombre", centroCosto);
		
		return (CentroCosto) query.uniqueResult();	
	}

}
